package com.tbynet.jwp.repository.impl;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;

import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.tbynet.jwp.framework.aop.Aop;
import com.tbynet.jwp.framework.core._JwpServiceProvider;
import com.tbynet.jwp.model.TermTaxonomy;
import com.tbynet.jwp.repository.spi.TermTaxonomyService;

/**
 * 分类法服务实现类
 * @ClassName: TermTaxonomyServiceProvider
 * @Description: 负责分类法数据的获取、添加、修改、删除功能的具体实现，职责单一
 * @Author: 佰亿互联
 * @Date: 2025年11月4日
 *
 * @Copyright: 2025 www.tbynet.com Inc. All rights reserved.
 * 注意: 本内容仅限于内部传阅，禁止外泄以及用于其他的商业目
 */
@Aop(TermTaxonomyService.class)
public class TermTaxonomyServiceImpl extends _JwpServiceProvider<TermTaxonomy> implements TermTaxonomyService {

    @Override
    protected String buildSearchWhereSql(String keyword, List<Object> params) {
        return "";
    }

    // ============ 查询相关方法实现 ============

    @Override
    public TermTaxonomy getTermTaxonomy(Object termId, String taxonomy) {
        if (termId == null || StrKit.isBlank(taxonomy)) {
            log.warn("参数错误：termId或taxonomy为空");
            return null;
        }

        String sql = "SELECT * FROM wp_term_taxonomy WHERE term_id=? AND taxonomy=? LIMIT 1";
        return getDao().findFirst(sql, termId, taxonomy);
    }

    @Override
    public List<TermTaxonomy> getTermTaxonomies(String taxonomy) {
        if (StrKit.isBlank(taxonomy)) {
            log.warn("参数错误：taxonomy为空");
            return new ArrayList<>();
        }

        String sql = "SELECT * FROM wp_term_taxonomy WHERE taxonomy=? ORDER BY term_taxonomy_id DESC";
        return getDao().find(sql, taxonomy);
    }

    @Override
    public Page<TermTaxonomy> search(int pageNumber, int pageSize, String taxonomy, String q) {
        if (StrKit.isBlank(taxonomy)) {
            log.warn("参数错误：taxonomy为空");
            return new Page<>(new ArrayList<>(), pageNumber, pageSize, 0, 0);
        }

        List<Object> paras = new ArrayList<>();
        StringBuilder sql = new StringBuilder("FROM wp_term_taxonomy tt " +
                "INNER JOIN wp_terms t ON tt.term_id = t.term_id " +
                "WHERE tt.taxonomy=?");
        paras.add(taxonomy);

        if (StrKit.notBlank(q)) {
            sql.append(" AND t.name LIKE ?");
            paras.add("%" + q + "%");
        }
        sql.append(" ORDER BY tt.term_taxonomy_id DESC");

        return getDao().paginate(pageNumber, pageSize, "SELECT tt.*, t.name", sql.toString(), paras.toArray());
    }

    // ============ 删除相关方法实现 ============

    @Override
    public boolean deleteTermTaxonomy(Object termId, String taxonomy) {
        if (termId == null || StrKit.isBlank(taxonomy)) {
            log.warn("参数错误：termId或taxonomy为空");
            return false;
        }

        try {
            String sql = "DELETE FROM wp_term_taxonomy WHERE term_id=? AND taxonomy=?";
            int result = Db.update(sql, termId, taxonomy);

            if (result > 0) {
                log.info("删除分类法成功，termId: {}, taxonomy: {}", termId, taxonomy);
                return true;
            } else {
                log.warn("删除分类法失败，未找到匹配记录，termId: {}, taxonomy: {}", termId, taxonomy);
                return false;
            }
        } catch (Exception e) {
            log.error("删除分类法异常，termId: {}, taxonomy: {}", termId, taxonomy, e);
            return false;
        }
    }

    // ============ 检查相关方法实现 ============

    @Override
    public boolean hasChildren(Object termId, String taxonomy) {
        if (termId == null || StrKit.isBlank(taxonomy)) {
            log.warn("参数错误：termId或taxonomy为空");
            return false;
        }

        try {
            String sql = "SELECT COUNT(*) FROM wp_term_taxonomy WHERE parent=? AND taxonomy=?";
            Long count = Db.queryLong(sql, termId, taxonomy);
            return count != null && count > 0;
        } catch (Exception e) {
            log.error("检查分类是否有子分类失败，termId: {}, taxonomy: {}", termId, taxonomy, e);
            return false;
        }
    }

    @Override
    public Number getParent(Object termId, String taxonomy) {
        if (termId == null || StrKit.isBlank(taxonomy)) {
            log.warn("参数错误：termId或taxonomy为空");
            return null;
        }

        try {
            String sql = "SELECT parent FROM wp_term_taxonomy WHERE term_id=? AND taxonomy=? LIMIT 1";
            return Db.queryNumber(sql, termId, taxonomy);
        } catch (Exception e) {
            log.error("获取分类父级ID失败，termId: {}, taxonomy: {}", termId, taxonomy, e);
            return null;
        }
    }

    // ============ 工具方法实现 ============

    @Override
    public boolean updateChildrenParent(Object termId, String taxonomy, Object newParent) {
        if (termId == null || StrKit.isBlank(taxonomy) || newParent == null) {
            log.warn("参数错误：termId、taxonomy或newParent为空");
            return false;
        }

        try {
            String sql = "UPDATE wp_term_taxonomy SET parent=? WHERE parent=? AND taxonomy=?";
            int result = Db.update(sql, newParent, termId, taxonomy);
            log.info("更新子分类父级完成，termId: {}, newParent: {}, 影响行数: {}", termId, newParent, result);
            return result >= 0;
        } catch (Exception e) {
            log.error("更新子分类父级失败，termId: {}, newParent: {}", termId, newParent, e);
            return false;
        }
    }

    @Override
    public TermTaxonomy getOrCreateTermTaxonomy(Object termId, String taxonomy) {
        if (termId == null || StrKit.isBlank(taxonomy)) {
            log.warn("参数错误：termId或taxonomy为空");
            return null;
        }

        // 先尝试获取已存在的分类法
        TermTaxonomy termTaxonomy = getTermTaxonomy(termId, taxonomy);
        if (termTaxonomy != null) {
            return termTaxonomy;
        }

        // 创建新的分类法
        termTaxonomy = new TermTaxonomy();
        termTaxonomy.setTaxonomy(taxonomy);
        termTaxonomy.setTermId(new BigInteger(termId.toString()));
        termTaxonomy.setDescription("");
        termTaxonomy.setParent(BigInteger.ZERO);
        termTaxonomy.setCount(0L);

        if (termTaxonomy.save()) {
            log.info("创建新分类法成功，termId: {}, taxonomy: {}", termId, taxonomy);
            return termTaxonomy;
        } else {
            log.error("创建新分类法失败，termId: {}, taxonomy: {}", termId, taxonomy);
            return null;
        }
    }

    @Override
    public TermTaxonomy getTermTaxonomyByNameAndTaxonomy(String name, String taxonomy) {
        if (StrKit.isBlank(name) || StrKit.isBlank(taxonomy)) {
            log.warn("参数错误：name或taxonomy为空");
            return null;
        }

        String sql = "SELECT tt.* FROM wp_terms t " +
                "INNER JOIN wp_term_taxonomy tt ON t.term_id = tt.term_id " +
                "WHERE t.name=? AND tt.taxonomy=? LIMIT 1";
        return getDao().findFirst(sql, name, taxonomy);
    }

    // ============ 重写父类方法 ============

    @Override
    public Page<TermTaxonomy> search(int pageNumber, int pageSize, String keyword) {
        // 默认搜索所有分类法
        return search(pageNumber, pageSize, "", keyword);
    }

    @Override
    protected String getDefaultOrderBy() {
        return "term_taxonomy_id DESC";
    }
}